package driver;

import state.Globals;
import driver.actions.BaseAction;

public class ActionHandlerThread implements Runnable {
    
    private boolean shouldContinue = true;
    private Thread runThread;
    private boolean isBusy = true;
    
    private BaseAction workItem = null;
    
    public ActionHandlerThread()
    {
        runThread = new Thread(this);
    }
    
    public synchronized boolean isBusy()
    {
        return isBusy;
    }
    
    public synchronized boolean setWorkItem(BaseAction action)
    {
        if (!isBusy)
        {
            
            workItem = action;
            isBusy = true;
            
            notify();
            
            return true;
            
        }
        return false;
    }
    
    public void start()
    {
        runThread.start();
    }
    
    public Thread getThread()
    {
        return runThread;
    }
    
    @Override
    public void run()
    {
        while (shouldContinue)
        {
            synchronized (this)
            {
                isBusy = false;
                
                ActionDriver.getInstance().notifyCompletion();
                
                try
                {
                    wait();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            
            if (!shouldContinue)
            {
                break;
            }
            
            if (workItem == null)
            {
                continue;
            }
            
            if (Globals.isDebug())
            {
                Globals.getLogger().log("Performing action: " + workItem);
            }
            
            workItem.performAction();
            
            workItem = null;
        }
    }
    
    public void shutdown()
    {
        shouldContinue = false;
        
        synchronized (this)
        {
            notify();
        }
        
        try
        {
            runThread.join();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

}
